package cqrtplm.service.impl;


import com.ty.basic.entity.org.UserDO;
import com.ty.basic.service.snow.SnowflakeIdComponent;
import com.ty.basic.session.TyAccountContext;
import cqrtplm.constant.RTErrorCodeEnum;
import cqrtplm.entity.RtComSupplierDO;
import cqrtplm.mapper.RtComSupplierMapper;
import cqrtplm.service.RtComSupplierService;
import cqrtplm.util.RTLogHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Slf4j
@Service
public class RtComSupplierServiceImpl implements RtComSupplierService {

    @Resource
    private RtComSupplierMapper rtComSupplierMapper;

    @Resource
    private SnowflakeIdComponent snowflakeIdComponent;

    @Resource
    private RTLogHelper rtLogHelper;

    @Override
    public List<RtComSupplierDO> selectRtComSupplierList(RtComSupplierDO rtComSupplier) {
        return rtComSupplierMapper.selectRtComSupplierList(rtComSupplier);
    }

    @Override
    public RtComSupplierDO selectRtComSupplierById(String id) {
        return rtComSupplierMapper.selectRtComSupplierById(id);
    }

    @Override
    public RtComSupplierDO selectRtComSupplierByCode(String supplierCode) {
        return rtComSupplierMapper.selectRtComSupplierByCode(supplierCode);
    }

    @Override
    public int insertRtComSupplier(RtComSupplierDO rtComSupplier) {
        String supplierCode = rtComSupplier.getSupplierCode();
        RtComSupplierDO old = rtComSupplierMapper.selectRtComSupplierByCode(supplierCode);
        if(old != null) {
            throw RTErrorCodeEnum.DATA_EXISTS.getException("该供应商编码已存在");
        }

        UserDO user = TyAccountContext.getUser();
        if (user == null) {
            throw new RuntimeException("用户未登录");
        }

        String snowId = String.valueOf(snowflakeIdComponent.getInstance().nextId());
        rtComSupplier.setId(snowId);

        return rtComSupplierMapper.insertRtComSupplier(rtComSupplier);
    }

    @Override
    public int updateRtComSupplier(RtComSupplierDO rtComSupplier) {
        RtComSupplierDO old = rtComSupplierMapper.selectRtComSupplierById(rtComSupplier.getId());
        if(old == null) {
            throw RTErrorCodeEnum.DATA_NOT_EXISTS.getException("该供应商不存在");
        }

        int r = rtComSupplierMapper.updateRtComSupplier(rtComSupplier);
        return r;
    }

    @Override
    public int deleteRtComSupplierById(String id) {
        return rtComSupplierMapper.deleteRtComSupplierById(id);
    }

    @Override
    public int deleteRtComSupplierByIds(List<String> ids) {
        return rtComSupplierMapper.deleteRtComSupplierByIds(ids);
    }
}